package order

import (
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"shopstar/models"
	"shopstar/models/order"
	"shopstar/util"
	"strconv"
	"time"
)

/**
 * @Com www.sixstaredu.com
 * @Author 六星教育-shineyork老师
 */

type Order struct{}

var OrderService = new(Order)

func (*Order) CreateOrder(userId string, shopid int, totalAmount decimal.Decimal, orderGoods []*order.OrderGoods) (err error) {
	err = models.DB.Transaction(func(tx *gorm.DB) error {
		orderNo := OrderService.orderNo()

		// 生成订单编号
		// 总金额
		// 计算实际支付金额
		discountAmount := decimal.NewFromInt(0)
		actualAmount := totalAmount.Sub(discountAmount)
		// 运费等计算
		freight := decimal.NewFromInt(0)
		// actualAmount.Cmp(decimal.NewFromInt(0))
		// -1 <
		// 0 =
		// 1 >
		if cmp := actualAmount.Cmp(decimal.NewFromInt(0)); cmp == -1 {
			actualAmount = decimal.NewFromInt(0)
		}
		var orderStatus byte = 0

		var payMethod byte = 0
		// 支付信息记录
		// 创建店铺主订单
		o := order.Order{
			OrderNo:            orderNo,
			UserId:             userId,
			ShopId:             shopid,
			PlaceTime:          time.Now(),
			PayMethod:          payMethod,
			PayNo:              "",
			DistributionMethod: 0,
			DistributionTime:   time.Now(),
			TotalAmount:        totalAmount,
			DiscountsAmount:    discountAmount,
			ActualAmount:       actualAmount,
			Freight:            freight,
			Ramark:             "",
			RefundStatus:       0,
			RefundNo:           "",
			Status:             orderStatus,
			ItemCount:          len(orderGoods),
			GoodsDetail:        nil,
		}
		if err := models.DB.Create(&o).Error; err != nil {
			return err
		}

		// 完善 orderGoods
		for k, _ := range orderGoods {
			orderGoods[k].OrderId = o.Id
			// 还需要考虑额外计算
		}

		err = models.DB.Create(&orderGoods).Error
		if err != nil {
			return err
		}
		// ..
		return nil
	})

	return
}

func (*Order) orderNo() string {
	timeNow := util.TimeNow(util.TIMESTR)
	rand := util.RInt(89999) + 10000
	return timeNow + strconv.Itoa(rand)
}
